package cn.maihe.elg.operation.service.business;


import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CustomerAttachmentTypeEnum;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDOCondition;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;

/**
 * @Description
 * @Author caixh
 * @Date 2021/8/9.
 */
@Service
@Slf4j
public class CustomerAttachmentService extends BaseDaoService<CustomerAttachmentDO> {

    @Resource
    private ImageUploadConfig imageUploadConfig;
    @Resource
    private ElgResourceService elgResourceService;

    public List<CustomerAttachmentDO> getAttachmentDO(Long bidderId, String type) {
        CustomerAttachmentDOCondition condition = CustomerAttachmentDOCondition.builder().andBidderIdEq(bidderId);
        if (StringUtils.isNotEmpty(type)) {
            condition.andAttachTypeEq(type);
        }
        List<CustomerAttachmentDO> customerAttachmentDOS = MybatisDaoImpl.run().selectList(condition.build());
        customerAttachmentDOS.forEach(attach -> {
            attach.setAttachPath(Constants.REGIST_IMAGE_PATH + attach.getAttachFileName());
        });
        return customerAttachmentDOS;
    }

    public String getRelationPath(String filePath) {
        return Constants.REGIST_IMAGE_PATH + filePath;
    }

    public Path getBidBusinessLicFile(Long bidderId,CenterNoEnum centerNoEnum,String clientId) {
        List<CustomerAttachmentDO> quaList = getAttachmentDO(bidderId, CustomerAttachmentTypeEnum.TYPE_0.getType());
        String attachFileName;
        if(CreateGuaranteeUtil.isDefaultBusinessLicense(centerNoEnum,clientId)){
            if(CollectionUtils.isEmpty(quaList)){
                attachFileName = "9171f8e9-97f1-4c98-979d-1a73b94f9707.png";
            } else {
                attachFileName = quaList.get(0).getAttachFileName();
            }
        } else {
            Assert.notEmpty(quaList, () -> "投标人营业执照不能为空");
            CustomerAttachmentDO quaObj = quaList.get(0);
            attachFileName = quaObj.getAttachFileName();
        }

        return getCustomerAttachPathByFileName(attachFileName);
    }

    public Path getBidQualificationFile(Long bidderId,CenterNoEnum centerNoEnum,String clientId) {
        List<CustomerAttachmentDO> quaList = getAttachmentDO(bidderId, CustomerAttachmentTypeEnum.TYPE_7.getType());
        String attachFileName;
        if(CreateGuaranteeUtil.isDefaultBusinessLicense(centerNoEnum,clientId)){
            if (CollectionUtils.isEmpty(quaList)) {
                attachFileName = "4f219a51-7ef7-4310-bc65-9f4a35deddb6.jpg";
            } else {
                attachFileName =  quaList.get(0).getAttachFileName();
            }
        } else {
            Assert.notEmpty(quaList, () -> "投标人资质文件不能为空");
            CustomerAttachmentDO quaObj = quaList.get(0);
            attachFileName =  quaObj.getAttachFileName();
        }

        return getCustomerAttachPathByFileName(attachFileName);
    }

    /**
     * 默认存放在 baseResource/upload/image/regist/ + fileName
     */
    private Path getCustomerAttachPathByFileName(String fileName) {
        String relativePath = String.format("/upload/image/regist/%s", fileName);
        return elgResourceService.getFileByRelativePath(relativePath).toPath();
    }


    /**
     * 获取附件的base64字符串
     *
     * @param attachmentList
     * @param attachmentTypeEnum
     * @return
     */
    public String getBase64Str(List<CustomerAttachmentDO> attachmentList, CustomerAttachmentTypeEnum attachmentTypeEnum) {

        CustomerAttachmentDO customerAttachmentDO = attachmentList.stream().filter(l -> attachmentTypeEnum.getType().equals(l.getAttachType())).findFirst().orElseThrow(() -> new RuntimeException("查无此附件[" + attachmentTypeEnum.getDesc() + "]"));
        String attachFileName = customerAttachmentDO.getAttachFileName();
        if (StringUtils.isBlank(attachFileName)) {
            return null;
        }

        String baseDir = imageUploadConfig.getPath();
        Path absolutePath = Paths.get(baseDir + Constants.REGIST_IMAGE_PATH + attachFileName);
        if (Files.notExists(absolutePath)) {
            throw new RuntimeException("文件不存在[" + absolutePath.toString() + "]");
        }

        try {
            return Base64.getEncoder().encodeToString(Files.readAllBytes(absolutePath));
        } catch (IOException e) {
            throw new RuntimeException("文件转base64异常:" + e.getMessage(), e);
        }

    }

    public CustomerAttachmentDO getCustomerAttachment(Long bidderId, CustomerAttachmentTypeEnum type) {
        CustomerAttachmentDOCondition condition = CustomerAttachmentDOCondition.builder().andBidderIdEq(bidderId).andAttachTypeEq(type.getType());
        return this.selectOne(condition.build());
    }

}
